#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python 3.13 兼容性修复工具
解决NumPy、PyInstaller与Python 3.13的兼容性问题
"""

import os
import sys
import subprocess
import shutil
import platform

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"当前Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major == 3 and version.minor == 13:
        print("✅ 检测到Python 3.13，将使用兼容性修复方案")
        return True
    else:
        print("⚠️ 非Python 3.13版本，可能不需要此修复脚本")
        return False

def fix_numpy_compatibility():
    """修复NumPy兼容性"""
    print("\n🔧 修复NumPy兼容性...")
    
    try:
        # 卸载旧版本NumPy
        print("1. 卸载旧版本NumPy...")
        subprocess.run([sys.executable, "-m", "pip", "uninstall", "numpy", "-y"], 
                      check=False, capture_output=True)
        
        # 安装兼容Python 3.13的NumPy
        print("2. 安装兼容的NumPy版本...")
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", 
            "numpy>=2.1.0", "--no-cache-dir"
        ], check=True, capture_output=True, text=True)
        
        # 验证安装
        test_result = subprocess.run([
            sys.executable, "-c", 
            "import numpy as np; print(f'NumPy版本: {np.__version__}')"
        ], capture_output=True, text=True)
        
        if test_result.returncode == 0:
            print(f"✅ NumPy安装成功: {test_result.stdout.strip()}")
            return True
        else:
            print(f"❌ NumPy验证失败: {test_result.stderr}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"❌ NumPy安装失败: {e}")
        return False

def fix_pyinstaller_compatibility():
    """修复PyInstaller兼容性"""
    print("\n🔧 修复PyInstaller兼容性...")
    
    try:
        # 卸载旧版本PyInstaller
        print("1. 卸载旧版本PyInstaller...")
        subprocess.run([sys.executable, "-m", "pip", "uninstall", "pyinstaller", "-y"], 
                      check=False, capture_output=True)
        
        # 尝试安装最新的PyInstaller
        print("2. 安装最新的PyInstaller...")
        result = subprocess.run([
            sys.executable, "-m", "pip", "install", 
            "pyinstaller>=6.11.0", "--no-cache-dir"
        ], check=False, capture_output=True, text=True)
        
        if result.returncode == 0:
            # 验证安装
            test_result = subprocess.run([
                sys.executable, "-c", 
                "import PyInstaller; print(f'PyInstaller版本: {PyInstaller.__version__}')"
            ], capture_output=True, text=True)
            
            if test_result.returncode == 0:
                print(f"✅ PyInstaller安装成功: {test_result.stdout.strip()}")
                return True
        
        # 如果官方版本失败，尝试开发版本
        print("3. 尝试安装PyInstaller开发版...")
        dev_result = subprocess.run([
            sys.executable, "-m", "pip", "install", 
            "https://github.com/pyinstaller/pyinstaller/archive/develop.zip",
            "--no-cache-dir"
        ], check=False, capture_output=True, text=True)
        
        if dev_result.returncode == 0:
            print("✅ PyInstaller开发版安装成功")
            return True
        else:
            print("❌ PyInstaller开发版安装失败")
            return False
            
    except Exception as e:
        print(f"❌ PyInstaller安装过程出错: {e}")
        return False

def install_alternative_packager():
    """安装替代打包工具"""
    print("\n🔧 安装替代打包工具: cx_Freeze...")
    
    try:
        subprocess.run([
            sys.executable, "-m", "pip", "install", 
            "cx_Freeze>=6.15.0", "--no-cache-dir"
        ], check=True)
        
        print("✅ cx_Freeze安装成功")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ cx_Freeze安装失败: {e}")
        return False

def create_cx_freeze_setup():
    """创建cx_Freeze设置文件"""
    setup_content = '''#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cx_Freeze 打包配置
适用于Python 3.13
"""

import sys
from cx_Freeze import setup, Executable

# 包含的模块
includes = [
    "PyQt5.QtCore", "PyQt5.QtGui", "PyQt5.QtWidgets",
    "numpy", "pandas", "matplotlib", "openpyxl", "psutil",
    "xml.etree.ElementTree", "logging"
]

# 排除的模块
excludes = [
    "tkinter", "unittest", "test", "distutils",
    "email", "http", "urllib", "xml.dom", "xml.sax"
]

# 包含的文件
include_files = [
    "frame_schema.xml",
    "logger.py",
    "frame_processor.py", 
    "visualization.py",
    "progress_dialog.py",
    "frame_schema_parser.py",
    "log_analyzer.py"
]

# 可执行文件配置
executables = [
    Executable(
        "main.py",
        base="Win32GUI" if sys.platform == "win32" else None,
        target_name="成帧数据应用软件.exe" if sys.platform == "win32" else "成帧数据应用软件",
        icon=None  # 如果有图标文件，可以指定路径
    )
]

setup(
    name="成帧数据应用软件",
    version="1.0.0",
    description="成帧数据分析和处理软件",
    author="Your Name",
    options={
        "build_exe": {
            "includes": includes,
            "excludes": excludes,
            "include_files": include_files,
            "optimize": 2,
            "include_msvcrt": True,
        }
    },
    executables=executables
)
'''
    
    with open("setup_cxfreeze.py", "w", encoding="utf-8") as f:
        f.write(setup_content)
    
    print("✅ 已创建cx_Freeze配置文件: setup_cxfreeze.py")

def update_requirements():
    """更新依赖文件以支持Python 3.13"""
    print("\n🔧 更新依赖配置...")
    
    # 安装兼容的依赖
    try:
        subprocess.run([
            sys.executable, "-m", "pip", "install", 
            "-r", "requirements_py313.txt", "--no-cache-dir"
        ], check=True)
        print("✅ 依赖更新成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖更新失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("Python 3.13 兼容性修复工具")
    print("=" * 60)
    
    # 检查Python版本
    is_py313 = check_python_version()
    
    if not is_py313:
        response = input("是否继续执行修复？(y/N): ")
        if response.lower() != 'y':
            return
    
    success_count = 0
    total_steps = 4
    
    # 1. 修复NumPy
    if fix_numpy_compatibility():
        success_count += 1
    
    # 2. 更新所有依赖
    if update_requirements():
        success_count += 1
    
    # 3. 修复PyInstaller
    if fix_pyinstaller_compatibility():
        success_count += 1
    else:
        print("⚠️ PyInstaller修复失败，将使用cx_Freeze作为替代方案")
        
    # 4. 安装替代工具
    if install_alternative_packager():
        create_cx_freeze_setup()
        success_count += 1
    
    print("\n" + "=" * 60)
    print(f"修复完成: {success_count}/{total_steps} 步骤成功")
    
    if success_count >= 3:
        print("✅ 基本修复成功！建议的下一步操作：")
        print("1. 如果PyInstaller可用，运行: python -m PyInstaller 成帧数据应用软件.spec")
        print("2. 如果PyInstaller不可用，运行: python setup_cxfreeze.py build")
        print("3. 检查生成的可执行文件是否正常工作")
    else:
        print("❌ 修复过程中遇到多个问题")
        print("建议解决方案：")
        print("1. 降级到Python 3.11或3.12")
        print("2. 使用虚拟环境重新安装")
        print("3. 考虑在Docker容器中进行打包")
    
    print("=" * 60)

if __name__ == "__main__":
    main() 